#!/usr/bin/env python
import ez_setup, os
ez_setup.use_setuptools()
from setuptools import setup
from setuptools import Command 

from xadmin import version
app_name = 'django-xadmin'
app_dir = 'xadmin'
author_email = 'mockbuddha@gmail.com'
author = 'mockbuddha'


class GoogleUpload(Command):
    """
        upload builded to google repository.
        
        credential could be saved in the same 'setup.cfg' of distutils or $HOME/.pypyrc.
        
        WARNING!!! syntax is NOT same as standard upload
        
        [repository_as_passed_to_cmdline]
        username=
        password=
        host=  <<< change the host for this repository_as_passed_to_cmdline. 
                    Can be used to aliasing or naming repositories
    """
    description = "upload to google code repository"
    DEFAULT_REPOSITORY = "http://code.google.com/p/%s/downloads/entry" % app_name
    DEFAULT_LABELS =  'Featured,Type-Source,OpSys-All'
    
    user_options = [
        ('repository=', 'r', "url of repository [default: %s]" % DEFAULT_REPOSITORY),
        ('message=', 'm', "commit log"),
        ('labels=', 'l', """labels to tag the commit (comma-separated list) 
                        [default: %s]""" % DEFAULT_LABELS),
        ('debug', None, 'display full response text from server'),
        ('username=', 'u', ''),
        ('password=', 'p', ''),
        ]
    boolean_options = ['debug']
    
    def __init__ (self, dist):
        
        Command.__init__(self, dist)
        
    def initialize_options(self):
        self.username = ''
        self.password = ''
        self.repository = ''
        self.message = None
        self.debug = 0
        self.labels = self.DEFAULT_LABELS
            
    def finalize_options(self):
        import ConfigParser
        if not self.repository:
            self.repository = self.DEFAULT_REPOSITORY
        
        if not self.message:
            raise DistutilsOptionError("please set message log")
        
        self.ensure_string_list('labels')

        cfg_files = self.distribution.find_config_files()
        cfg_files.append(os.path.join(os.environ['HOME'], '.pypirc') )
        for cfg in cfg_files:
            if os.path.exists( cfg ):
                config = ConfigParser.ConfigParser({
                        'username':'',
                        'password':'',
                        'host':self.DEFAULT_REPOSITORY})
                config.read( cfg )
                try:
                    if not (self.username and self.password):
                        self.username = config.get(self.repository, 'username')
                        self.password = config.get(self.repository, 'password')
                        self.repository = config.get(self.repository, 'host')
                        if self.debug:
                            print "found %s in %s" % (self.repository, cfg)
                        break
                except ConfigParser.NoSectionError:
                    if self.debug:
                        print "No config found in %s for %s" % (cfg, self.repository)
            elif self.debug:
                print "No config found at %s" % (cfg,)
    
    def run(self):
        if not self.distribution.dist_files:
            raise DistutilsOptionError("No dist file created in earlier command")
        
        for command, pyversion, filename in self.distribution.dist_files:
            self.upload_file(filename)
            
    def upload_file(self, filename):
        from googlecode_upload import upload
        status, reason, url = upload( filename, app_name, self.username, self.password, self.message, self.labels )
        print status, reason, url


root_dir = os.path.dirname(__file__)

if root_dir != '':
    os.chdir(root_dir)

def scan_dir(target):
    _packages, _data_files = [], []
    for dirpath, dirnames, filenames in os.walk(target):
        # Ignore dirnames that start with '.'
        for i, dirname in enumerate(dirnames):             
            if dirname.startswith('.'): del dirnames[i]
        if '__init__.py' in filenames:
            pkg = dirpath.replace(os.path.sep, '.')
            if os.path.altsep:
                pkg = pkg.replace(os.path.altsep, '.')
            _packages.append(pkg)
        elif filenames:
            _data_files.append([dirpath, [os.path.join(dirpath, f) for f in filenames]])
    return _packages, _data_files


packages, templates = scan_dir( app_dir )         
discard, media_files = scan_dir( 'media' )

setup(      
    #include_package_data = True,
    name=app_name,
    version=version,
    packages = packages,
    data_files = templates + media_files,
    zip_safe=False,
    author= author,
    author_email= author_email,
    description=" ",
    long_description="",
    license="MIT License",
    keywords="django extended admin",
    platforms=['any'],
    url="http://code.google.com/p/%s/" % app_name,
    download_url="http://code.google.com/p/%s/downloads/list" % app_name,
    cmdclass={"upload": GoogleUpload},
)

